package cn.aiseminar.aisentry;

import cn.aiseminar.aisentry.AISpeakingService.AISpeakingBinder;
import cn.aiseminar.aisentry.communicate.AISBBS;
import cn.aiseminar.aisentry.reader.BookShelfActivity;
import cn.aiseminar.aisentry.transceiver.Transceiver;
import cn.aiseminar.aisentry.transceiver.Transceiver.DataTransferThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class AISEntryActivity extends Activity implements ServiceConnection {
	
    private Transceiver mTransceiver = null;
    
    private ViewFlipper mViewFlipper = null;
    private GestureDetector mGestureDetector = null;
    
    private View mEntryView = null;
    private View mReaderView = null;
    private View mCircleMenuView = null;
    
    private AISystemLoader mSystemLoader = null;
    
    private AISpeakingService mSpeakingService = null;
    private Handler mMouthMsgHandler = null;
    
    ImageButton btnConnectEntry = null;
    ImageButton btnBookReader = null;
    ImageButton btnChatBot = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        requestWindowFeature(Window.FEATURE_NO_TITLE); // hidden title        
        setContentView(R.layout.activity_aisentry);
        
        mGestureDetector = new GestureDetector(this, new AISOnGestureListener());
        mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipper);
        
        mEntryView = findViewById(R.id.entryImage);
        mEntryView.setLongClickable(true);
        mEntryView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {				
				return mGestureDetector.onTouchEvent(event);
			}
		});
        
        mReaderView = findViewById(R.id.readerView);
        mReaderView.setLongClickable(true);
        mReaderView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {				
				return mGestureDetector.onTouchEvent(event);
			}
		});
        
        mTransceiver = new Transceiver(this);
        
        // for circle menu
        mCircleMenuView = findViewById(R.id.circleMenu);
        mCircleMenuView.setVisibility(View.INVISIBLE);
        
        btnConnectEntry = (ImageButton)findViewById(R.id.btnConnectEntry);
        btnBookReader = (ImageButton)findViewById(R.id.btnBookReader);
        btnChatBot = (ImageButton)findViewById(R.id.btnChatBot);
        
        OnClickListener circleMenuClickListener = new OnClickListener() {
			@Override
			public void onClick(View view) {
				mCircleMenuView.setVisibility(View.INVISIBLE);
				if (view == btnConnectEntry)
				{
					connectToEntry();
				}
				else if (view == btnBookReader)
				{
					openBookReader();
				}
				else if (view == btnChatBot)
				{
//					openDeviceControl();
					openAISBBS();
				}
			}
		};
		
        btnConnectEntry.setOnClickListener(circleMenuClickListener);
        btnBookReader.setOnClickListener(circleMenuClickListener);
        btnChatBot.setOnClickListener(circleMenuClickListener);
        
//        initNotification();
    }

    @Override
	protected void onStart() {
		super.onStart();
		
		if (null == mSystemLoader)
		{
			mSystemLoader = new AISystemLoader(this);
			mSystemLoader.checkEnvironment();
		}
		
		if (null == mSpeakingService)
		{
			Intent serviceIntent = new Intent(AISEntryActivity.this, AISpeakingService.class);
//			bindService(serviceIntent, this, BIND_AUTO_CREATE);
			this.startService(serviceIntent);
		}
		resetMsgHandler();
	}
    
    @Override
	protected void onDestroy() {
		unbindService(this);
		super.onDestroy();
	}

	private void resetMsgHandler()
    {
    	if (null != mSpeakingService)
		{
    		mMouthMsgHandler = mSpeakingService.getMouthHandler();
			mSpeakingService.resetMouthHandler();
			mTransceiver.setMsgHandler(mMouthMsgHandler);
		}
    }
    
    private void connectToEntry()
    {
    	final EditText inputServer = new EditText(this);
    	inputServer.setHint(getLocalIpPrefix() + ".xxx" + ":xxxx");
    	inputServer.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				String serverInfo = inputServer.getText().toString();
				if (inputServer.hasFocus() && serverInfo.equals(""))
				{
					String prefix = getLocalIpPrefix() + ".";
					inputServer.setText(prefix);
//					Selection.setSelection(inputServer.getText(), prefix.length());
					inputServer.setSelection(prefix.length());
				}
			}
		});
    	
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("Connect to PC Entry").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer);
    	builder.setNegativeButton(android.R.string.cancel, null);
    	builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try 
				{
					String serverInfo = inputServer.getText().toString();
					int seperPos = serverInfo.indexOf(":");								
					String ipAddress = serverInfo.substring(0, seperPos);
					String ipPort = serverInfo.substring(seperPos + 1);
					
					mTransceiver.connectToEntry(ipAddress, Integer.parseInt(ipPort));
				}
				catch (Exception e)
				{
					Toast.makeText(AISEntryActivity.this, R.string.msg_error_ip_format, Toast.LENGTH_LONG).show();
					if (null != mMouthMsgHandler)
					{
						Message msg = new Message();
						msg.what = AISMessageCode.TRANSCEIVER_MSG_BASE + DataTransferThread.DATATYPE_PLAINTEXT;
						msg.obj = AISEntryActivity.this.getString(R.string.msg_error_ip_format);
						mMouthMsgHandler.sendMessage(msg);
					}
				}
			}
		});
    	builder.show();
    }
    
    private void openBookReader()
    {
    	Intent readerIntent = new Intent(AISEntryActivity.this, BookShelfActivity.class);
		startActivity(readerIntent);
    }
    
    private void openAISBBS()
    {
    	Intent aisBBSIntent = new Intent(AISEntryActivity.this, AISBBS.class);
		startActivity(aisBBSIntent);
    }
    
    private void openDeviceControl()
    {
    	Intent deviceControlIntent = new Intent(AISEntryActivity.this, AISDeviceControl.class);
		startActivity(deviceControlIntent);
    }
    
    private String getLocalIpPrefix()
    {
    	WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    	WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    	int ip = wifiInfo.getIpAddress();
    	return (ip & 0xFF ) + "." 
    			+ (ip >> 8  & 0xFF) + "."
    			+ (ip >> 16 & 0xFF);
    }
    
    public String getLocalIP()
    {
    	WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    	WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    	int ipAddress = wifiInfo.getIpAddress();
    	return intToIp(ipAddress);
    }
    
    private String intToIp(int ip) 
    {
    	return (ip & 0xFF ) + "." 
    			+ (ip >> 8  & 0xFF) + "." 
    			+ (ip >> 16 & 0xFF) + "." 
    			+ (ip >> 24 & 0xFF) ;
    } 
	
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId())
		{
			case R.id.itemSpeechSetting:
				Intent speechIntent = new Intent(this, AISpeechSetting.class);
				startActivity(speechIntent);
//				Intent settingIntent = new Intent();
//				settingIntent.setClassName(this, "com.iflytek.speechcloud.activity.speaker.SpeakerSetting");
//				startActivity(settingIntent);
				break;
		}
		
		return super.onOptionsItemSelected(item);
	}
    
    class AISOnGestureListener extends SimpleOnGestureListener
    {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			int fling_min_distance = 100;
			int fling_min_velocity = 200;
			
			if (Math.abs(velocityX) > fling_min_velocity)
			{
				if (e1.getX() - e2.getX() > fling_min_distance) // right in
				{
					if (mViewFlipper.getCurrentView() == mReaderView)
					{
						mViewFlipper.setInAnimation(AISEntryActivity.this, R.anim.anim_right_in);
						mViewFlipper.setOutAnimation(AISEntryActivity.this, R.anim.anim_left_out);
						mViewFlipper.showPrevious();
					}
				}
				else if (e2.getX() - e1.getX() > fling_min_distance) // left in
				{
					if (mViewFlipper.getCurrentView() == mEntryView)
					{
						mViewFlipper.setInAnimation(AISEntryActivity.this, R.anim.anim_left_in);
						mViewFlipper.setOutAnimation(AISEntryActivity.this, R.anim.anim_right_out);
						mViewFlipper.showNext();
					}
				}
			}
			
			return super.onFling(e1, e2, velocityX, velocityY);
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			if (mViewFlipper.getCurrentView() == mEntryView)
			{
				if (View.VISIBLE == mCircleMenuView.getVisibility())
				{
					mCircleMenuView.setVisibility(View.INVISIBLE);
				}
				else
				{
					mCircleMenuView.setVisibility(View.VISIBLE);
				}
			}
			else if (mViewFlipper.getCurrentView() == mReaderView)
			{
				openBookReader();
			}
			return super.onSingleTapConfirmed(e);
		} 
		
    }

	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		AISpeakingBinder speakingBinder = (AISpeakingBinder) service;
		mSpeakingService = speakingBinder.getSpeakingService();
		resetMsgHandler();
	}

	@Override
	public void onServiceDisconnected(ComponentName arg0) {
		mSpeakingService = null;		
	}
	
    private void initNotification()
    {
    	Intent intent = new Intent(this, AISEntryActivity.class);
    	PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    	
    	Notification n = new Notification.Builder(this)
    			.setContentTitle("AISEntry")
    			.setContentText("朗读功能启动，复制文字将自动为您朗读。")
    			.setContentIntent(contentIntent)
    			.setSmallIcon(android.R.drawable.ic_menu_share)
    			.build();
    	NotificationManager mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    	mNM.notify(1001, n);
    }
}
